<template>
    <div class="ant_layout">
        <!-- 左侧边栏 -->
        <div class="layout_sider">
            <!-- 区划树 -->
            <DataTree :treeData="apiTreeData" @changeRegionCode="changeRegionCodeFn" />
        </div>

        <!-- 主体 -->
        <div class="layout_content">
            <!-- 顶部按钮 -->
            <div class="content_opertors">
                <div class="left">
                    <a-button type="primary" @click="mainQuery">查询</a-button>
                    <a-button type="primary" @click="generateReport">重新生成报告</a-button>
                    <a-button type="primary" @click="exportExcel(dataSource, columns, '预测数预警（月）.xlsx')">导出</a-button>
                </div>
                <div class="right">
                    <a-form :model="topForm" name="basic" layout="inline" autocomplete="off">
                        <a-form-item label="年度月份：" name="yearAndmonth" :rules="[{ required: true }]">
                            <a-date-picker v-model:value="topForm.yearAndmonth" picker="month" placeholder="---请选择---" style="width: 100px" @change="dateChangeFn" />
                        </a-form-item>
                        <a-form-item label="金额单位：" name="amt_unit" :rules="[{ required: true }]">
                            <a-select v-model:value="topForm.amt_unit" style="width: 80px" @change="amtChangeFn">
                                <a-select-option :value="1">元</a-select-option>
                                <a-select-option :value="10000">万元</a-select-option>
                                <a-select-option :value="100000000">亿元</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-form>
                    <a-switch v-model:checked="tableOrEcharts" checked-children="图" un-checked-children="表" />
                </div>
            </div>
            <!-- 反馈区域 -->
            <div class="feedbackInfo">
                <div>
                    <a-popover>
                        <template #content>
                            <img src="./Image/warningDsc.png" alt="" style="width: 460px" />
                        </template>
                        <a-button size="small">预警等级：</a-button>
                    </a-popover>

                    <template v-if="wranQuota">
                        <a-tag v-if="wranQuota.warn_level == 0">正常</a-tag>
                        <a-tag v-else :color="wranQuota.warn_color">{{ wranQuota.warn_color_cn }}</a-tag>
                    </template>
                </div>
                <div>
                    <span>库款差额：</span>
                    <span v-cloak>{{ toThousands(treasuryCE) }}</span>
                </div>
            </div>
            <!-- 表格区域 -->
            <!-- 以下注释是添加复选框和分页，功能已经实现 -->
            <!-- :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }" :pagination="pagination" -->
            <div class="grid" :class="{ showOrhide: tableOrEcharts }">
                <a-table
                    :columns="columns"
                    :data-source="dataSource"
                    :rowKey="(record) => record.itemIndex"
                    bordered
                    size="small"
                    :scroll="{ y: '64vh' }"
                    :pagination="false"
                    :loading="loading"
                    @resizeColumn="handleResizeColumn"
                >
                    <template #bodyCell="{ text, record, index, column }">
                        <!-- 序号列 -->
                        <!-- <template v-if="column.key === 'itemIndex'">
                            {{ (pagination.current - 1) * pagination.pageSize + (index + 1) }}
                        </template> -->
                        <template v-if="column.dataIndex === 'corrAmt'">
                            <div class="editable-cell">
                                <div v-if="editableData[index]" class="editable-cell-input-wrapper">
                                    <a-input style="width: 70%; margin-right: 10px" v-model:value="editableData[index].corrAmt" @pressEnter="save(index)" />
                                    <check-outlined class="editable-cell-icon-check" @click="save(index)" />
                                </div>
                                <div v-else class="editable-cell-text-wrapper">
                                    <span style="width: 70%; margin-right: 10px">{{ toThousands(text) || ' ' }}</span>
                                    <edit-outlined class="editable-cell-icon" @click="edit(index)" />
                                </div>
                            </div>
                        </template>
                    </template>
                </a-table>
            </div>
            <div class="my_echarts" :class="{ showOrhide: !tableOrEcharts }">
                <MyEchartsTwo :echartsData="echartsData" :echartsWarnData="echartsWarnData"></MyEchartsTwo>
            </div>
            <div class="dsc_gird" :class="{ showOrhide: !tableOrEcharts }">
                <WarningDsc></WarningDsc>
            </div>
        </div>
    </div>
</template>

<script setup>
import DataTree from './Component/DataTree.vue';
import MyEchartsTwo from '@/views/TreasuryWarningPhoto/Component/MyEchartsTwo.vue';
import WarningDsc from '@/views/TreasuryWarningPhoto/Component/WarningDsc.vue';
import { ref, reactive, computed, watch, onMounted } from 'vue';
import { CheckOutlined, EditOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';
import { cloneDeep } from 'lodash';
import { findColmunRepeatValIndexArr, checkIsHave } from '@/util/tableUtils';
import { toTreeData, toThousands, exportExcel } from '@/util/common';
import { regionTreeQuery } from '@/request/api/commonAPI';
import { reportQuery, generateQuery, modifyCorrAmt, provinceWarningQuery } from '@/request/api/treasuryWarningPhoto';

// 右上角年度月份、金额单位表单数据
let topForm = reactive({
    yearAndmonth: dayjs(),
    amt_unit: 10000,
});

// 日期选择框事件
const dateChangeFn = (date, dateStr) => {
    topForm.yearAndmonth = date;
    mainQuery();
};

// 金额选择框事件
const amtChangeFn = (date, option) => {
    mainQuery();
};

// 预警等级、库款差额
let warningLevel = ref(null);
let wranQuota = ref(null);
let treasuryCE = ref(null);

let templateQuotas = [];

let markLineData = [];

const warningInfo = (warningLevel) => {
    if (warningLevel == 1) {
        return { warningName: '工资支出预警', warningColor: 'red' };
    }
    if (warningLevel == 2) {
        return { warningName: '三保支出预警', warningColor: 'orange' };
    }
    if (warningLevel == 3) {
        return { warningName: '还本付息支出预警', warningColor: 'yellow' };
    }
    if (warningLevel == 4) {
        return { warningName: '定向支出预警', warningColor: 'green' };
    }
};

const getMarkLineData = (templateQuotas) => {
    markLineData.length = 0;
    if (templateQuotas.length && templateQuotas.length > 0) {
        templateQuotas.forEach((item, index) => {
            markLineData.push({
                name: warningInfo(item.warn_level).warningName,
                yAxis: item.warn_amt,
                lineStyle: { color: warningInfo(item.warn_level).warningColor, type: 'solid' },
            });
        });
    }
};

// 左侧区划树选中的区划code
const regionCode = ref([]);

const changeRegionCodeFn = (data) => {
    regionCode.value = data;
    mainQuery();
};

/**
 * 表格相关
 */
// 分页
const pageSizeChange = (val, pageNum) => {
    pagination.pageSize = pageNum;
    pagination.current = 1;
    // const params = {
    //     rows: pagination.pageSize,
    //     page: pagination.current,
    // };
};
const pageChange = (page, val) => {
    pagination.current = page;
    // const params = {
    //     rows: pagination.pageSize,
    //     page: pagination.current,
    // };
    // queryFun();
};
const pagination = reactive({
    current: 1,
    pageSize: 50,
    showSizeChanger: true,
    total: 0,
    pageSizeOptions: ['50', '100', '200', '500'],
    showTotal: (total) => `共 ${total} 条数据`,
    onShowSizeChange: pageSizeChange,
    onChange: pageChange,
});

// dataSource
let dataSource = ref([]);
// 表头
const columns = ref([
    {
        title: '序号',
        dataIndex: 'itemIndex',
        key: 'itemIndex',
        width: 60,
        align: 'center',
        resizable: true,
        // customRender: ({text, record, index}) => index + 1,
        // customRender: ({ text, record, index }) => `${(pagination.current - 1) * pagination.pageSize + (index + 1)}`,
    },
    {
        title: '分类',
        dataIndex: 'itemGroup',
        key: 'itemGroup',
        width: 200,
        align: 'center',
        resizable: true,
        customCell: (_, index) => {
            console.log(typeof index);
            let repeatItemArr = findColmunRepeatValIndexArr(dataSource.value, 'itemGroup');
            let curColumnRepeatArr = checkIsHave(index, repeatItemArr);
            if (curColumnRepeatArr && curColumnRepeatArr.indexOf(index) === 0) {
                return { rowSpan: curColumnRepeatArr.length };
            }
            if (curColumnRepeatArr && curColumnRepeatArr.indexOf(index) > 0) {
                return { rowSpan: 0 };
            }
        },
    },
    {
        title: '项目',
        dataIndex: 'itemName',
        key: 'itemName',
        width: 300,
        align: 'left',
        resizable: true,
    },
    {
        title: '上报数',
        dataIndex: 'planAmt',
        key: 'planAmt',
        width: 200,
        align: 'right',
        resizable: true,
        customRender: ({ text }) => {
            return toThousands(text);
        },
    },
    {
        title: '确认数',
        dataIndex: 'corrAmt',
        key: 'corrAmt',
        resizable: true,
        width: 200,
        align: 'right',
    },
]);
// 拖动列宽
const handleResizeColumn = (w, col) => {
    col.width = w;
};
// 加载动画
let loading = ref(false);
// 复选框
const state = reactive({
    selectedRowKeys: [],
});
const hasSelected = computed(() => state.selectedRowKeys.length > 0);
const onSelectChange = (selectedRowKeys, selectedRows) => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    console.log('selectedRowKeys changed: ', selectedRows);
    state.selectedRowKeys = selectedRowKeys;
};
// 可编辑
const editableData = reactive({});
const edit = (key) => {
    editableData[key] = cloneDeep(
        dataSource.value.filter((item, index) => {
            return key === index;
        })[0]
    );
};
const save = (key) => {
    Object.assign(dataSource.value.filter((item, index) => key === index)[0], editableData[key]);
    Object.assign(cloneDeepData['value']['details'].filter((item, index) => key === index)[0], editableData[key]);
    delete editableData[key];
    modifyCorrAmt(cloneDeepData.value, { amtUnit: topForm.amt_unit }).then((res) => {
        if (res.state == '200') {
            message.success(res.msg || '修改成功！');
        } else {
            message.error(res.msg || '修改失败！');
        }
        mainQuery();
    });
};

// 区划树数据
const apiTreeData = reactive([]);

// 查询左侧边栏区划树
const regionTreeData = () => {
    const params = {
        reportDate: dayjs(topForm.yearAndmonth).format('YYYY-MM'),
        warnCycle: 3,
    }
    regionTreeQuery(params).then((res) => {
        if (res.state == '200') {
            const { hotData, data } = res;
            const apiTreeDataArr = toTreeData(data);
            apiTreeData.length = 0
            apiTreeDataArr.forEach(item => {
                apiTreeData.push(item)
            })
            // console.log(JSON.stringify(apiTreeData.value));

            message.success(res.msg || '区划树查询成功！');
        } else {
            message.error(res.msg || '区划树查询失败！');
        }
    });
};

// 主查询
let cloneDeepData = ref({}); // 修改确认数的接口传参
const mainQuery = () => {
    Object.keys(editableData).map((key) => {
        delete editableData[key];
    });
    loading.value = true;
    let data = {
        amtUnit: topForm.amt_unit,
        reportDate: dayjs(topForm.yearAndmonth).format('YYYY-MM'),
        mofDivCode: regionCode['value'][0],
        warnCycle: 3,
    };
    if(data.mofDivCode != undefined) {
        reportQuery(data).then((res) => {
            loading.value = false;
            if (res.state == '200') {
                const { hotData, data } = res;
                cloneDeepData.value = cloneDeep(data);
                dataSource.value = data.details;
                templateQuotas.length ? (templateQuotas.length = 0) : null;
                data.template.quotas.forEach((item, index) => {
                    templateQuotas.push(item);
                });
                getMarkLineData(templateQuotas);
                wranQuota.value = data.wranQuota;
                warningLevel.value = data.wranQuota.warn_level;
                treasuryCE.value = data.neededAmt;
                regionTreeData() // 更新区划树预警状态
                message.success(res.msg || '报告查询成功！');
            } else {
                cloneDeepData.value = cloneDeep(data);
                dataSource.value = [];
                wranQuota.value = null;
                warningLevel.value = null;
                treasuryCE.value = null;
                message.error(res.msg || '报告查询失败！');
            }
        });
    }else {
        loading.value = false;
    }
};

// 重新生成报告
const generateReport = () => {
    let data = {
        amtUnit: topForm.amt_unit,
        reportDate: dayjs(topForm.yearAndmonth).format('YYYY-MM'),
        mofDivCode: regionCode['value'][0],
        warnCycle: 3,
    };
    generateQuery(data).then((res) => {
        if (res.state == '200') {
            message.success(res.msg || '报告生成成功！');
            mainQuery();
        } else {
            message.error(res.msg || '报告生成失败！');
        }
    });
}

// echarts相关
// 右上角，switch开关切换表格与图表的参数
let tableOrEcharts = ref(true);
// 传给echarts组件预警图的数据
const echartsData = reactive({
    // legendData: [
    //     {
    //         orient: 'vertical',
    //         x: 'left',
    //         selected: {'用于定向支出的收入项目':false},
    //         data: ['上级转移支付资金', '本月收入（含政府性基金收入）', '期初库款余额', '发债收入', '用于定向支出的收入项目', '    其中:新增专项债券(转贷)收入', '    再融资债券(转贷)收入'],
    //     },
    //     {
    //         orient: 'vertical',
    //         x: 'right',
    //         selected: {'三保支出预算数':false},
    //         data: ['对下转移性支出', '还本付息支出计划数', '三保支出预算数', '    其中：三保支出（除工资）', '    其中：工资支出预算数', '刚性支出', '定向支出'],
    //     },
    // ],
    legendData: {
        orient: 'vertical',
        left: 'left',
        selected: {'用于定向支出的收入项目':false,'三保支出预算数':false},
        // data: ['上级转移支付资金', '本月收入（含政府性基金收入）', '期初库款余额', '发债收入', '用于定向支出的收入项目', '    其中:新增专项债券(转贷)收入', '    再融资债券(转贷)收入','对下转移性支出', '还本付息支出计划数', '三保支出预算数', '    其中：三保支出（除工资）', '    其中：工资支出预算数', '刚性支出', '定向支出'],
        data: [
            {name:'上级转移支付资金',icon:'roundRect'},
            {name:'本月收入（含政府性基金收入）',icon:'roundRect'},
            {name:'期初库款余额',icon:'roundRect'},
            {name:'发债收入',icon:'roundRect'},
            {name:'用于定向支出的收入项目',icon:'roundRect'},
            {name:'    其中:新增专项债券(转贷)收入',icon:'roundRect'},
            {name:'    再融资债券(转贷)收入',icon:'roundRect'},
            {name:'对下转移性支出',icon:'circle'},
            {name:'还本付息支出计划数',icon:'circle'},
            {name:'三保支出预算数',icon:'circle'},
            {name:'    其中：三保支出（除工资）',icon:'circle'},
            {name:'    其中：工资支出预算数',icon:'circle'},
            {name:'刚性支出',icon:'circle'},
            {name:'定向支出',icon:'circle'}],
    },
    xAxisData: [dayjs(topForm.yearAndmonth).format('YYYY-MM')],
    seriesData: [],
});
// 监听表格数据，动态生成echarts预警柱图数据
watch(
    () => dataSource.value,
    (newValue, oldValue) => {
        // echartsData['legendData'][0]['data'].length = 0;
        // echartsData['legendData'][1]['data'].length = 0;
        echartsData['xAxisData'].length = 0;
        echartsData['xAxisData'].push(dayjs(topForm.yearAndmonth).format('YYYY-MM'));
        echartsData['seriesData'].length = 0;
        if (newValue.length > 0) {
            // console.log('newValue----', newValue);
            newValue.forEach((item, index, arr) => {
                if ((item['itemGroup'] == '期初数' || item['itemGroup'] == '本期流入') && item['itemName'] != '本期库款流入') {
                    // echartsData['legendData'][0]['data'].push(item['itemName']);
                    echartsData['seriesData'].push({
                        name: item['itemName'],
                        type: 'bar',
                        stack: 'AD',
                        data: [item['corrAmt'] ? Number(item['corrAmt']) : 0],
                        // markLine: markLineData.length
                        //     ? {
                        //           symbol: 'none', //去掉箭头
                        //           tooltip: { formatter: '{b}: {c}' },
                        //           label: { show: true, formatter: '{b}: {c}' },
                        //           data: markLineData,
                        //       }
                        //     : 'none',
                        markLine: warningLevel.value > 0
                            ? {
                                  symbol: 'none', //去掉箭头
                                  tooltip: { formatter: '{b}: {c}' },
                                  label: { show: true, formatter: '{b}: {c}' },
                                  data: markLineData,
                              }
                            : 'none',
                    });
                }
                if (item['itemGroup'] == '本期流出' && item['itemName'] != '本期库款流出') {
                    // echartsData['legendData'][1]['data'].push(item['itemName']);
                    echartsData['seriesData'].push({
                        name: item['itemName'],
                        type: 'bar',
                        stack: 'BD',
                        data: [item['corrAmt'] ? Number(item['corrAmt']) : 0],
                    });
                }
            });
        }

        if (echartsData['seriesData'].length != 0) {
            let tempArr = [];
            echartsData['seriesData'].forEach((item, index, arr) => {
                if (item['name'] == '上级转移支付资金') {
                    tempArr[6] = item;
                }
                if (item['name'] == '本月收入（含政府性基金收入）') {
                    tempArr[5] = item;
                }
                if (item['name'] == '期初库款余额') {
                    tempArr[4] = item;
                }
                if (item['name'] == '发债收入') {
                    tempArr[3] = item;
                }
                if (item['name'] == '用于定向支出的收入项目') {
                    tempArr[2] = item;
                }
                if (item['name'] == '    其中:新增专项债券(转贷)收入') {
                    tempArr[1] = item;
                }
                if (item['name'] == '    再融资债券(转贷)收入') {
                    tempArr[0] = item;
                }

                if (item['name'] == '对下转移性支出') {
                    tempArr[13] = item;
                }
                if (item['name'] == '还本付息支出计划数') {
                    tempArr[12] = item;
                }
                if (item['name'] == '三保支出预算数') {
                    tempArr[11] = item;
                }
                if (item['name'] == '    其中：三保支出（除工资）') {
                    tempArr[10] = item;
                }
                if (item['name'] == '    其中：工资支出预算数') {
                    tempArr[9] = item;
                }
                if (item['name'] == '刚性支出') {
                    tempArr[8] = item;
                }
                if (item['name'] == '定向支出') {
                    tempArr[7] = item;
                }
            });
            echartsData['seriesData'].length = 0;
            tempArr.forEach((item, index, arr) => {
                echartsData['seriesData'].push(item);
            });
        }
    },
    { deep: true }
);

// 传给echarts组件库款差额图的数据
const echartsWarnData = reactive({
    xAxisData:[],
    seriesColor: [],
    seriesData: []
})
// 监听wranQuota，动态生成echarts库款差额柱图数据
watch(
  () => wranQuota.value, (newVal, oldVal)=> {
    if(wranQuota.value != null){
        let params = {
            amtUnit: topForm.amt_unit,
            reportDate: dayjs(topForm.yearAndmonth).format('YYYYMM'),
            mofDivCode: regionCode['value'][0],
        };
        provinceWarningQuery(params).then((res) => {
            if (res.state == '200') {
                if(res.data && res.data.length > 0) {
                    let warnData = cloneDeep(res.data[0])
                    delete warnData['mof_div_code'];
                    delete warnData['mof_div_name'];
                    echartsWarnData.xAxisData = Object.keys(warnData);
                    echartsWarnData.seriesColor = Object.keys(warnData);
                    echartsWarnData.seriesData = Object.values(warnData).map(item => {
                        return Math.abs(item);
                    });
                }else {
                    echartsWarnData.xAxisData.length = 0;
                    echartsWarnData.seriesColor.length = 0;
                    echartsWarnData.seriesData.length = 0;
                }
                // message.success(res.msg || '库款差额查询成功！');
            } else {
                message.error(res.msg || '库款差额查询失败！');
            }
        });
    }
  },
  { deep: true }
)

onMounted(() => {
    // 查询左侧边栏区划树
    regionTreeData();
    // 主查询，查询报告
    // mainQuery();
});
</script>

<style lang="less" scoped>
.showOrhide {
    display: none;
}
.ant_layout {
    display: flex;
    justify-content: space-between;
    height: 100%;
    width: 100%;

    .layout_sider {
        display: inline-block;
        padding: 20px;
        height: 100%;
        width: 20%;
        border: 2px solid #f6f6f6;
        overflow: auto;
    }

    .layout_content {
        display: inline-block;
        // flex: 1;
        padding: 20px;
        width: 80%;
        height: 100%;
        border: 2px solid #f6f6f6;
        overflow: auto;

        .content_opertors {
            display: flex;
            justify-content: space-between;
            height: 32px;
            margin-bottom: 20px;

            .left .ant-btn {
                margin-right: 16px;
            }

            .right {
                display: flex;
                .ant-form-item {
                    margin-bottom: 0;
                }
                .ant-switch {
                    background-color: #1890ff;
                }
            }
        }

        .grid {
            margin-top: 20px;
            height: calc(100% - 98px);
        }
        .my_echarts {
            margin-top: 20px;
            // height: calc(100% - 196px);
            background-color: #f1eeeb59;
        }
        .my_echarts > div {
            display: flex;
            justify-content: space-around;
        }
        :deep(.dsc_gird td) {
            background-color: #f1eeeb59 !important;
        }

        :deep(.ant-table-cell) {
            overflow: hidden;
        }

        :deep(.ant-table-body) {
            height: 100%;
        }
    }

    .feedbackInfo div {
        display: inline-block;
        margin-right: 20px;
        .ant-btn {
            margin-right: 2px;
        }
    }
}
</style>
